<template>
  <div>
    <!--  麵包屑  類似於：首页/活动管理/活动列表/活动详情  -->
    <el-breadcrumb separator="/" style="padding-left:10px;padding-bottom:10px;font-size:14px;">
        <!--   聲明式導航：to相結合一起使用   -->
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>系统管理</el-breadcrumb-item>
      <el-breadcrumb-item>部门管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <!--      搜索區域-->
      <!--   gutter是指栅格间间隔，offset是指栅格左侧的间隔格数         -->
      <el-row :gutter="20">
        <el-col :span="8"><!-- 栅格占据的8列数 -->
          <el-input
            size="small"
            clearable
            v-model="queryMap.name"
            placeholder="请输入部门查询"
            @clear="search"
            class="input-with-select"
          >
            <el-button slot="append" icon="el-icon-search" @click="search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="2">
          <el-button
            size="small"
            v-hasPermission="'department:add'"
            type="success"
            icon="el-icon-circle-plus-outline"
            @click="addDialogVisible=true"
          >添加</el-button>
        </el-col>
      </el-row>
  <!--  部门列表数据   -->
    <template>
      <el-table
    border
    size="small"
    v-loading="loading"
    stripe
    :data="departmentData"
    style="width: 100%;margin-top:20px;"
    height="460"
  >
    <!--       <el-table-column  列-->
    <el-table-column prop="id" type="index" label="ID" width="50"></el-table-column>
    <el-table-column prop="phone" label="办公电话" width="180"></el-table-column>
    <el-table-column prop="name" label="部门名" width="120"></el-table-column>
    <el-table-column prop="total" label="人数" sortable width="100">
      <template slot-scope="scope">
        <el-tag effect="plain"  v-text="scope.row.total +'人'" size="small">
        </el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="createTime" label="创建时间" sortable></el-table-column>
    <el-table-column prop="modifiedTime" label="修改时间" sortable></el-table-column>
    <el-table-column prop="address" label="地址"></el-table-column>
    <el-table-column label="操作">
      <template slot-scope="scope">
        <el-button
          v-hasPermission="'department:edit'"
          type="text"
          size="small"
          icon="el-icon-edit"
          @click="edit(scope.row.id)"
        >编辑</el-button>
        <!--     v-hasPermission="'department:delete'"  数据库表menu 表中配置权限，有权限就显示这个button按钮    -->
        <el-button
          v-hasPermission="'department:delete'"
          type="text"
          size="small"
          icon="el-icon-delete"
          @click="del(scope.row.id)"
        >删除</el-button>
      </template>
    </el-table-column>
  </el-table>
    </template>
    <!--    分頁-->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="this.queryMap.pageNum"
      :page-sizes="[10, 20, 40]"
      :page-size="this.queryMap.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>


      <!-- 部门别添加弹出框 -->
      <el-dialog title="添加部门" :visible.sync="addDialogVisible" width="50%" @close="closeAddDialog">
        <span>
          <el-form
            :model="addRuleForm"
            :rules="addRules"
            ref="addRuleFormRef"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item label="部门名称" prop="name">
              <el-input v-model="addRuleForm.name"></el-input>
            </el-form-item>
            <el-form-item label="办公电话" prop="phone">
              <el-input v-model="addRuleForm.phone"></el-input>
            </el-form-item>
            <el-form-item label="办公地址" prop="address">
              <el-input type="textarea" v-model="addRuleForm.address"></el-input>
            </el-form-item>
          </el-form>
        </span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="add" :disabled="btnDisabled" :loading="btnLoading">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
    export default {
      name: "Dept",
      data(){
        const checkPhone = (rule, value, callback) => {

          const phoneReg = /^1[34578]\d{9}$$/;
          if (!value) {
            return callback(new Error("电话号码不能为空"));
          }
          setTimeout(() => {
            if (!Number.isInteger(+value)) {
              callback(new Error("请输入数字值"));
            } else {
              //校驗 手機號碼符不符合規範
              if (phoneReg.test(value)) {
                callback();
              } else {
                callback(new Error("电话号码格式不正确"));
              }
            }
          }, 100);
        };
          return{
            loading: false, //动态加载的效果
            departmentData:[],//后台返回的数据存放在这里
            queryMap:{pageNum:1, pageSize:10,name:''},
            total:0,
            addDialogVisible:false,
            addRuleForm:{},
            btnDisabled:false,
            btnLoading:false,
            addRules:{
              name: [
                { required: true, message: "请输入部门名称", trigger: "blur" },
                { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" }
              ],
              address: [
                { required: true, message: "请输入办公地址", trigger: "blur" },
                { min: 4, max: 12, message: "长度在 4 到 12 个字符", trigger: "blur" }
              ],
              phone: [
                {
                  required: true,
                  message: "请输入正確的手機號碼",
                  validator: checkPhone, // 使用正则表达式验证手机号是否正确
                  trigger: "blur"
                }
              ]
            } //添加验证
          }
      },
      methods:{
        closeAddDialog(){
          this.$refs.addRuleFormRef.clearValidate()
          this.addRuleForm = {}
        },
        add(){
          this.$refs.addRuleFormRef.validate((valid)=>{
            if(!valid){
              return;
            }else{
             const {data:res} = this.$http.post( "system/department/add",this.addRuleForm)
              if (res.success) {
                  this.$message.success("部门添加成功");
                  this.addRuleForm = {};//將部門添加的表單置為空
                  this.getDepartmentList();//添加成功後去獲取部門信息列表數據
                } else {
                  return this.$message.error("部门添加失败:" + res.data.errorMsg);
                }
                this.addDialogVisible = false;//隱藏彈框
                 // btnDisabled  確認按鈕置為灰色，不可以去點擊
                (this.btnLoading = false), (this.btnDisabled = false);
              }
          })
        },
        edit(id){

        },
        del(id){
          console.log(id)
          this.$confirm('此操作将永久删除该部門數據, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            const {data:res} = this.$http.get("system/department/delete/" + id)
            if(res.success){
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              this.getDepartmentList()
            }
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });
          });

        },
        async getDepartmentList(){
          let {data :res }  = await this.$http.get(
            'system/department/findDepartmentList', { params:this.queryMap}  )
          if(res.success){
            this.departmentData = res.data.rows
            this.total = res.data.total;
          }
        },
        handleSizeChange(val) {
          console.log(`每页 ${val} 条`);
          this.queryMap.pageSize = val;
          this.getDepartmentList();
        },
        handleCurrentChange(val) {
          console.log(`当前页: ${val}`);
          this.queryMap.pageNum = val
          this.getDepartmentList();
        },
        search(){
          console.log(this.queryMap.name)
          this.getDepartmentList();
        }
      },
      created(){
        //页面创建的时候去访问后，获取列表数据
        this.getDepartmentList();
      }
    }
</script>

<style scoped>

</style>
